<template>
  <div class="pet-manage-container">
    <h1 class="page-title">🐾 宠物信息管理</h1>

    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="宠物名称">
          <el-input v-model="searchForm.petName" placeholder="请输入宠物名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="狗" :value="1"></el-option>
            <el-option label="猫" :value="2"></el-option>
            <el-option label="兔子" :value="3"></el-option>
            <el-option label="其他" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品种">
          <el-input v-model="searchForm.breed" placeholder="请输入品种" clearable></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="searchForm.gender" placeholder="请选择" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="公" :value="1"></el-option>
            <el-option label="母" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.petStatus" placeholder="请选择" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="待售" :value="1"></el-option>
            <el-option label="已售" :value="2"></el-option>
            <el-option label="已被领养" :value="3"></el-option>
            <el-option label="已预定" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄范围">
          <el-input-number v-model="searchForm.minAge" :min="0" placeholder="最小" controls-position="right" style="width: 130px;"></el-input-number>
          <span style="margin: 0 10px;">-</span>
          <el-input-number v-model="searchForm.maxAge" :min="0" placeholder="最大" controls-position="right" style="width: 130px;"></el-input-number>
        </el-form-item>
        <el-form-item label="价格范围">
          <el-input-number v-model="searchForm.minPrice" :min="0" placeholder="最低" controls-position="right" style="width: 130px;"></el-input-number>
          <span style="margin: 0 10px;">-</span>
          <el-input-number v-model="searchForm.maxPrice" :min="0" placeholder="最高" controls-position="right" style="width: 130px;"></el-input-number>
        </el-form-item>
        <el-form-item label="健康状态">
          <el-select v-model="searchForm.healthStatus" placeholder="请选择" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="健康" :value="1"></el-option>
            <el-option label="一般" :value="2"></el-option>
            <el-option label="需要关注" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="疫苗状态">
          <el-select v-model="searchForm.vaccinationStatus" placeholder="请选择" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="未接种" :value="0"></el-option>
            <el-option label="已接种" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="绝育状态">
          <el-select v-model="searchForm.sterilizationStatus" placeholder="请选择" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="未绝育" :value="0"></el-option>
            <el-option label="已绝育" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="排序">
          <el-select v-model="searchForm.orderBy" placeholder="排序字段" clearable style="width: 120px;">
            <el-option label="默认" value=""></el-option>
            <el-option label="价格" value="price"></el-option>
            <el-option label="年龄" value="age"></el-option>
            <el-option label="创建时间" value="createTime"></el-option>
          </el-select>
          <el-select v-model="searchForm.order" placeholder="排序方向" style="width: 100px; margin-left: 10px;">
            <el-option label="降序" value="desc"></el-option>
            <el-option label="升序" value="asc"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增宠物</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 宠物列表 -->
    <el-card style="margin-top: 20px;">
      <el-table :data="petList" v-loading="loading" stripe>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column label="图片" width="80">
          <template slot-scope="scope">
            <el-image
              :src="scope.row.image"
              :preview-src-list="[scope.row.image]"
              style="width: 50px; height: 50px; border-radius: 4px;">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="breed" label="品种"></el-table-column>
        <el-table-column prop="age" label="年龄">
          <template slot-scope="scope">
            {{ scope.row.age }}个月
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别"></el-table-column>
        <el-table-column prop="price" label="价格">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="录入时间" width="160"></el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template slot-scope="scope">
            <el-button-group>
              <el-button size="mini" type="primary" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
              <el-button size="mini" type="warning" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog title="宠物详情" :visible.sync="viewDialogVisible" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="宠物名称">{{ viewPetData.name }}</el-descriptions-item>
        <el-descriptions-item label="品种">{{ viewPetData.breed }}</el-descriptions-item>
        <el-descriptions-item label="类型">{{ viewPetData.species }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ viewPetData.gender }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ viewPetData.age }}个月</el-descriptions-item>
        <el-descriptions-item label="体重">{{ viewPetData.weight }}kg</el-descriptions-item>
        <el-descriptions-item label="颜色">{{ viewPetData.color }}</el-descriptions-item>
        <el-descriptions-item label="生日">{{ viewPetData.birthday }}</el-descriptions-item>
        <el-descriptions-item label="是否绝育">{{ viewPetData.isNeutered ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="芯片号">{{ viewPetData.microchipNumber }}</el-descriptions-item>
        <el-descriptions-item label="过敏史" :span="2">{{ viewPetData.allergies || '无' }}</el-descriptions-item>
        <el-descriptions-item label="特殊需求" :span="2">{{ viewPetData.specialNeeds || '无' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ formatDate(viewPetData.createTime) }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer">
        <el-button type="primary" @click="viewDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px">
      <el-form :model="petForm" :rules="petRules" ref="petForm" label-width="100px">
        <el-form-item label="宠物名称" prop="name">
          <el-input v-model="petForm.name" placeholder="请输入宠物名称"></el-input>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品种" prop="breed">
              <el-input v-model="petForm.breed" placeholder="请输入品种"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="petForm.age" :min="0" :max="300" style="width: 100%"></el-input-number>
              <span style="margin-left: 10px">个月</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="petForm.gender">
                <el-radio label="公">公</el-radio>
                <el-radio label="母">母</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model.number="petForm.price" placeholder="请输入价格">
                <template slot="prepend">¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="疫苗情况">
          <el-input v-model="petForm.vaccine" placeholder="请输入疫苗情况"></el-input>
        </el-form-item>

        <el-form-item label="健康状况">
          <el-input v-model="petForm.health" placeholder="请输入健康状况"></el-input>
        </el-form-item>

        <el-form-item label="描述">
          <el-input type="textarea" v-model="petForm.description"
                    :rows="3" placeholder="请输入宠物描述"></el-input>
        </el-form-item>

        <el-form-item label="图片上传">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAdminPetList } from '@/api/pet'
import salePetApi from '@/api/salePet'

export default {
  name: 'PetManage',
  data () {
    return {
      searchForm: {
        petName: '',
        categoryId: null,
        breed: '',
        gender: null,
        petStatus: null,
        minAge: null,
        maxAge: null,
        minPrice: null,
        maxPrice: null,
        healthStatus: null,
        vaccinationStatus: null,
        sterilizationStatus: null,
        dateRange: null,
        orderBy: '',
        order: 'desc'
      },
      petList: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      viewDialogVisible: false,
      dialogTitle: '新增宠物',
      petForm: {
        name: '',
        breed: '',
        age: 0,
        gender: '公',
        price: 0,
        vaccine: '',
        health: '',
        description: ''
      },
      viewPetData: {},
      petRules: {
        name: [{ required: true, message: '请输入宠物名称', trigger: 'blur' }],
        breed: [{ required: true, message: '请输入品种', trigger: 'blur' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.loadPetList()
  },
  methods: {
    async loadPetList () {
      this.loading = true
      try {
        // 构建查询参数
        const params = {
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        }
        
        // 添加筛选条件（只添加有值的参数）
        if (this.searchForm.petName) {
          params.petName = this.searchForm.petName
        }
        if (this.searchForm.categoryId !== null && this.searchForm.categoryId !== '') {
          params.categoryId = this.searchForm.categoryId
        }
        if (this.searchForm.breed) {
          params.breed = this.searchForm.breed
        }
        if (this.searchForm.gender !== null && this.searchForm.gender !== '') {
          params.gender = this.searchForm.gender
        }
        if (this.searchForm.petStatus !== null && this.searchForm.petStatus !== '') {
          params.petStatus = this.searchForm.petStatus
        }
        // 年龄范围
        if (this.searchForm.minAge !== null && this.searchForm.minAge !== '') {
          params.minAge = this.searchForm.minAge
        }
        if (this.searchForm.maxAge !== null && this.searchForm.maxAge !== '') {
          params.maxAge = this.searchForm.maxAge
        }
        // 价格范围
        if (this.searchForm.minPrice !== null && this.searchForm.minPrice !== '') {
          params.minPrice = this.searchForm.minPrice
        }
        if (this.searchForm.maxPrice !== null && this.searchForm.maxPrice !== '') {
          params.maxPrice = this.searchForm.maxPrice
        }
        // 健康状态
        if (this.searchForm.healthStatus !== null && this.searchForm.healthStatus !== '') {
          params.healthStatus = this.searchForm.healthStatus
        }
        // 疫苗状态
        if (this.searchForm.vaccinationStatus !== null && this.searchForm.vaccinationStatus !== '') {
          params.vaccinationStatus = this.searchForm.vaccinationStatus
        }
        // 绝育状态
        if (this.searchForm.sterilizationStatus !== null && this.searchForm.sterilizationStatus !== '') {
          params.sterilizationStatus = this.searchForm.sterilizationStatus
        }
        // 日期范围
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startDate = this.searchForm.dateRange[0]
          params.endDate = this.searchForm.dateRange[1]
        }
        // 排序
        if (this.searchForm.orderBy) {
          params.orderBy = this.searchForm.orderBy
          params.order = this.searchForm.order
        }
        
        console.log('查询参数:', params)
        const res = await getAdminPetList(params)
        console.log('后端返回数据:', res)
        
        // 处理响应数据
        const data = (res.data && res.data.records) || (res.data && res.data.list) || res.data || []
        this.petList = data.map(item => {
          let createTime = item.createTime || item.create_time || ''
          if (createTime) {
            createTime = createTime.split('T')[0].split(' ')[0]
          }
          return {
            id: item.id,
            name: item.petName || item.pet_name || item.name || '未命名',
            breed: item.breed || '未知品种',
            age: item.age || 0,
            gender: item.genderText || item.gender_text || this.getGenderText(item.gender),
            price: item.price || 0,
            image: item.mainImage || item.main_image || item.imageUrl || item.image_url || '',
            status: item.petStatusText || item.pet_status_text || this.getPetStatusText(item.petStatus || item.pet_status),
            createTime: createTime
          }
        })
        
        // 更新分页信息
        this.pagination.total = (res.data && res.data.total) || data.length || 0
      } catch (error) {
        console.error('加载失败:', error)
        this.$message.error('加载失败：' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },
    getGenderText (gender) {
      if (gender === 1 || gender === '1') return '公'
      if (gender === 2 || gender === '2') return '母'
      if (typeof gender === 'string') return gender
      return '未知'
    },
    getPetStatusText (status) {
      const statusMap = {
        1: '待售',
        2: '已售',
        3: '已被领养',
        4: '已预定'
      }
      return statusMap[status] || '未知'
    },
    handleSearch () {
      this.pagination.currentPage = 1
      this.loadPetList()
    },
    handleReset () {
      this.searchForm = {
        petName: '',
        categoryId: null,
        breed: '',
        gender: null,
        petStatus: null,
        minAge: null,
        maxAge: null,
        minPrice: null,
        maxPrice: null,
        healthStatus: null,
        vaccinationStatus: null,
        sterilizationStatus: null,
        dateRange: null,
        orderBy: '',
        order: 'desc'
      }
      this.pagination.currentPage = 1
      this.loadPetList()
    },
    handleAdd () {
      this.dialogTitle = '新增宠物'
      this.petForm = {
        name: '',
        breed: '',
        age: 0,
        gender: '公',
        price: 0,
        vaccine: '',
        health: '',
        description: ''
      }
      this.dialogVisible = true
    },
    async handleView (row) {
      try {
        const res = await salePetApi.getSalePetDetail(row.id)
        this.viewPetData = res.data || {}
        this.viewDialogVisible = true
      } catch (error) {
        this.$message.error('加载详情失败：' + (error.message || '未知错误'))
      }
    },
    async handleEdit (row) {
      try {
        const res = await salePetApi.getSalePetDetail(row.id)
        this.dialogTitle = '编辑宠物'
        const data = res.data || {}
        
        this.petForm = {
          id: data.id,
          name: data.name || '',
          breed: data.breed || '',
          age: data.age || 0,
          gender: data.gender || '公',
          price: parseFloat(data.price) || 0,
          vaccine: data.vaccine || '',
          health: data.health || '',
          description: data.description || ''
        }
        this.dialogVisible = true
      } catch (error) {
        this.$message.error('加载详情失败：' + (error.message || '未知错误'))
      }
    },
    handleDelete (row) {
      this.$confirm(`确认删除宠物 "${row.name}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await salePetApi.deleteSalePet(row.id)
          this.$message.success('删除成功')
          this.loadPetList()
        } catch (error) {
          this.$message.error('删除失败：' + (error.message || '未知错误'))
        }
      })
    },
    handleSubmit () {
      this.$refs.petForm.validate(async (valid) => {
        if (valid) {
          try {
            const submitData = {
              name: this.petForm.name,
              breed: this.petForm.breed,
              age: this.petForm.age,
              gender: this.petForm.gender,
              price: this.petForm.price,
              vaccine: this.petForm.vaccine,
              health: this.petForm.health,
              description: this.petForm.description
            }
            
            if (this.petForm.id) {
              await salePetApi.updateSalePet(this.petForm.id, submitData)
            } else {
              await salePetApi.addSalePet(submitData)
            }
            this.$message.success('操作成功')
            this.dialogVisible = false
            this.loadPetList()
          } catch (error) {
            this.$message.error('操作失败：' + (error.message || '未知错误'))
          }
        }
      })
    },
    formatDate (datetime) {
      if (!datetime) return '-'
      return datetime.split('T')[0].split(' ')[0]
    },
    getStatusType (status) {
      const typeMap = {
        '待售': 'success',
        '已售': 'info',
        '已被领养': 'warning',
        '已预定': 'warning'
      }
      return typeMap[status] || 'info'
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.loadPetList()
    },
    handleCurrentChange (val) {
      this.pagination.currentPage = val
      this.loadPetList()
    }
  }
}
</script>

<style scoped>
.pet-manage-container {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}
</style>
